--- title: "L2-002 链表去重" created: 2025-11-28 tags: - 算法 --- # L2-002 链表去重 ## 题目 [L2-002 链表去重](https://pintia.cn/problem-sets/994805046380707840/exam/problems/type/7?problemSetProblemId=994805072641245184&page=1) ![[image-b3946cfa.png]] ## 思路分析 ![[image-fbd3c515.png]] 尽力了孩子们 康复训练下马威 绞尽脑汁回忆起模拟链表怎么写 ![[image-39f0e16a.png]] ```cpp #include using namespace std; #define endl '\n' using ll = long long; using ull = unsigned long long; using PII = pair; using Pll = pair; int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1}; const int inf = 0x3f3f3f3f; unordered_map node; unordered_map del_node; int main(){ ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); int head,n;cin>>head>>n; while(n--){ int idx,var,next;cin>>idx>>var>>next; node[idx]={var,next}; } set have_exist; del_node[-1]={0,-1}; int curDelNail=-1; for(int i=head;i!=-1;i=node[i].second){ // cout< using namespace std; #define endl '\n' using ll = long long; using ull = unsigned long long; using PII = pair; using Pll = pair; int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1}; const int inf = 0x3f3f3f3f; unordered_map node; int main(){ ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); int head,n;cin>>head>>n; while(n--){ int idx,var,next;cin>>idx>>var>>next; node[idx]={var,next}; } set seen_abs; int del_head = -1, del_tail = -1; int prev = -1; // 前驱节点地址 int curr = head; // 当前节点地址 while(curr!=-1){ int curr_abs=abs(node[curr].first); if (seen_abs.count(curr_abs)) { // 需要删除当前节点 if (prev != -1) { node[prev].second = node[curr].second; // 前驱跳过当前节点 } else { head = node[curr].second; // 更新头节点 } // 将当前节点加入删除链表 if (del_head == -1) { del_head = del_tail = curr; } else { node[del_tail].second = curr; del_tail = curr; } node[curr].second = -1; // 断开原有连接 curr = node[prev].second; // 移动到下一个节点 } else { seen_abs.insert(curr_abs); prev = curr; curr = node[curr].second; } } for(int i=head;i!=-1;i=node[i].second){ printf("%05d %d ", i, node[i].first); if (node[i].second == -1) printf("-1\n"); else printf("%05d\n", node[i].second); } for(int i=del_head;i!=-1;i=node[i].second){ printf("%05d %d ", i, node[i].first); if (node[i].second == -1) printf("-1\n"); else printf("%05d\n", node[i].second); } return 0; } ``` ## 同类题型 ## 视频讲解 --- ⬅️ [[L2-001 紧急救援|L2-001 紧急救援]] 🏠 [[00-天梯赛]] ➡️ [[L2-003 月饼|L2-003 月饼]]